package webview

import (
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util"
	"gitee.com/snxamdf/wui/util/w"
	"html/template"
	"sync"
)

var widgetLock sync.RWMutex
var widgetListen = map[string]WidgetInterface{}

var goBindSyncJSTmpl = template.Must(template.New("goBindSyncJSTmpl").Parse(`GoBind.GoSyncJS("{{.Name}}", "{{.Id}}", "{{.Value}}");`))

type Widget struct {
	id        string
	value     w.WMap
	event     EventFn
	component ComponentInterface
}

//创建一个小控件
func NewWidget(widgetId string) WidgetInterface {
	wg := &Widget{
		id: widgetId,
	}
	//widgetListen[widgetId] = wg
	return wg
}
func (m *Widget) GetId() string {
	return m.id
}

func (m *Widget) Eval(js string) error {
	return m.component.GetWV().IEval(js)
}

type data struct {
	Name  string
	Id    string
	Value interface{}
}

// Go Sync JS Go 值改变同步到 JS
func (m *Widget) GoSyncJS() {
	widgetLock.Lock()
	defer widgetLock.Unlock()
	data := data{
		Name:  m.component.GetName(),
		Id:    m.id,
		Value: m.value,
	}
	//js := fmt.Sprintf(`GoBind.GoSyncJS("%s", "%s", "%v");`, m.component.GetName(), m.id, m.value)
	js, _ := util.HtmlTemplate(goBindSyncJSTmpl, data)
	if err := m.Eval(js); err != nil {
		logs.Error("GoSyncJS Error=>:", err)
	}
	logs.Debug("GoSyncJS", js)
}

//获取组件小控件所属的组件
func (m *Widget) GetComponent() ComponentInterface {
	return m.component
}

//小控件的回调事件触发
func (m *Widget) CBEvent(fn EventFn) WidgetInterface {
	m.event = fn
	return m
}

func (m *Widget) GetEvent() EventFn {
	return m.event
}

//获取小控件的值
func (m *Widget) GetValue() w.WMap {
	return m.value
}

//设置小控件的值
func (m *Widget) SetValue(value interface{}) {
	m.value.PutValue(value)
	m.GoSyncJS()
}
